'use client'

import { Fragment, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { useForm } from 'react-hook-form'
import { FormInput } from '@/components/ui/form'
import { createReturn } from '@/actions/return'
import { useRouter } from 'next/navigation'

interface CreateReturnDialogProps {
  sale: any // 使用序列化后的类型
  open: boolean
  onClose: () => void
}

interface ReturnFormData {
  items: {
    saleItemId: number
    quantity: string
    reason: string
  }[]
}

export function CreateReturnDialog({ sale, open, onClose }: CreateReturnDialogProps) {
  const router = useRouter()
  const [submitting, setSubmitting] = useState(false)

  const { register, handleSubmit, formState: { errors } } = useForm<ReturnFormData>({
    defaultValues: {
      items: sale.items.map((item: any) => ({
        saleItemId: item.id,
        quantity: '0',
        reason: ''
      }))
    }
  })

  const onSubmit = async (data: ReturnFormData) => {
    try {
      setSubmitting(true)
      const result = await createReturn({
        saleId: sale.id,
        items: data.items.filter(item => parseInt(item.quantity) > 0)
      })
      if (result.success) {
        onClose()
        router.refresh()
      } else {
        alert(result.error)
      }
    } catch (error) {
      console.error('创建退货单失败:', error)
      alert('创建退货单失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Transition show={open} as={Fragment}>
      <Dialog onClose={onClose} className="relative z-50">
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/30" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-2xl transform overflow-hidden rounded-lg bg-white shadow-xl transition-all">
                <div className="border-b border-gray-200 bg-white px-6 py-4">
                  <Dialog.Title as="h3" className="text-lg font-medium text-gray-900">
                    创建退货单
                  </Dialog.Title>
                </div>

                <form onSubmit={handleSubmit(onSubmit)}>
                  <div className="bg-white px-6 py-6">
                    <div className="space-y-4">
                      <div className="grid grid-cols-2 gap-4 mb-4">
                        <div>
                          <dt className="text-sm font-medium text-gray-500">销售单号</dt>
                          <dd className="mt-1 text-sm text-gray-900">{sale.code}</dd>
                        </div>
                        <div>
                          <dt className="text-sm font-medium text-gray-500">销售时间</dt>
                          <dd className="mt-1 text-sm text-gray-900">
                            {new Date(sale.createdAt).toLocaleString()}
                          </dd>
                        </div>
                      </div>

                      <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                          <tr>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              商品名称
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              销售数量
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              退货数量
                            </th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                              退货原因
                            </th>
                          </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200">
                          {sale.items.map((item: any, index: number) => (
                            <tr key={item.id}>
                              <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                {item.product.name}
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                {item.quantity}
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                <FormInput
                                  type="number"
                                  className="w-20"
                                  error={errors.items?.[index]?.quantity?.message}
                                  {...register(`items.${index}.quantity`, {
                                    min: { value: 0, message: '不能小于0' },
                                    max: { value: item.quantity, message: '不能大于销售数量' }
                                  })}
                                />
                              </td>
                              <td className="px-6 py-4 whitespace-nowrap">
                                <FormInput
                                  error={errors.items?.[index]?.reason?.message}
                                  {...register(`items.${index}.reason`, {
                                    validate: (value, formValues) => {
                                      const quantity = parseInt(formValues.items[index].quantity)
                                      if (quantity > 0 && !value) {
                                        return '请输入退货原因'
                                      }
                                      return true
                                    }
                                  })}
                                />
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  <div className="border-t border-gray-200 bg-gray-50 px-6 py-4 flex justify-end gap-4">
                    <button
                      type="button"
                      onClick={onClose}
                      className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                    >
                      取消
                    </button>
                    <button
                      type="submit"
                      disabled={submitting}
                      className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
                    >
                      {submitting ? '提交中...' : '提交'}
                    </button>
                  </div>
                </form>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  )
} 